<template>
  <div :class="['search', {'clear': show}]">
    <Header ref="header" v-model="searchValue" arrow :fixed="true" :focus="focus" @search="enterHandle" @focus="focusHandle" @clear="clearHandle" />
    <div :class="['nav', {showClass: show}]">
      <NavFilter ref="navFilter" :nav-height="108">
        <NavBar slot="nav" horizontal media :space="false" :border-bottom="false" background-color="#00C8B4">
          <div v-for="(l,i) in list" :key="i" :class="['nav-item', {active:l.value === $route.name}]" @click.stop="clickSelectedHandle(l)">{{ l.label }}</div>
        </NavBar>
        <keep-alive>
          <router-view v-if="!show" :key="$route.fullPath" :search-value="searchValue" page-type="search" />
        </keep-alive>
      </NavFilter>
      <div v-show="show" class="search-panne">
        <div v-if="historyList.length>0">
          <div class="history-list">
            <Scroll vertical style="max-height: 100vh;">
              <div class="history-title">
                <p>搜索历史</p>
                <svg-icon icon-class="shanchulajixiang-solid" @click.native.stop="closeRemoveHandle" />
              </div>
              <div class="history-tags">
                <Tag v-for="(h,i) in historyList" :key="h.label + i" :label="h.label" :value="h.label" button closeable long-press @click="clickTagHandle(h)" @close="closeRemoveHandle(i)" />
              </div>
            </Scroll>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Header from '@/components/Header'
import NavBar from '@/components/NavBar'
import NavFilter from '@/components/NavFilter'
import Tag from '@/components/Tag'
import Scroll from '@/components/Scroll'
import { mapMutations, mapGetters } from 'vuex'
function throttle(fn, delay = 200) {
  let id
  return (...args) => {
    if (id) {
      return
    }
    id = setTimeout(() => {
      fn(...args)
      id = null
    }, delay)
  }
}
export default {
  name: 'Search',
  components: {
    Header,
    NavBar,
    NavFilter,
    Tag,
    Scroll
  },
  props: {
  },
  data() {
    return {
      searchValue: '',
      show: false,
      list: [
        { label: '商品', value: 'SearchProduct' },
        /* { label: '定制产品', value: 'SearchCustomization' },
        { label: '单空间方案', value: 'SearchSingle' },
        { label: '全屋方案', value: 'SearchWhole' }, */
        { label: '系列', value: 'SearchSerices' },
        { label: '方案', value: 'SearchSchemeNew' },
        { label: '图册', value: 'SearchAtlas' }
      ],
      // 历史列表
      historyList: []
    }
  },
  computed: {
    ...mapGetters('nav', ['focus']),
    showSearchPanne() {
      return this.show && this.searchValue !== ''
    }
  },
  watch: {
    show(v) {
      if (v) {
        sessionStorage.setItem('forbid', true)
        document.body.style.overflow = 'hidden'
        this.$refs.navFilter.closeHandle()
        this.$refs.navFilter.showNav = true
      } else {
        sessionStorage.removeItem('forbid')
        document.body.style.overflow = 'inherit'
      }
    }
  },
  created() {
    this.show = false
  },
  mounted() {
    this.updateFocus(false)
  },
  beforeDestroy() {
    this.updateFocus(true)
  },
  activated() {
    if (this.searchValue === '') {
      this.searchValue = ''
      this.updateFocus(false)
      this.clearHandle()
      this.updateFilterData([])
    }
  },
  deactivated() {
    this.show = false
  },
  beforeRouteLeave(to, from, next) {
    const names = ['HomeIndex', 'GoodsIndex']
    if (names.includes(to.name)) {
      this.$removeKeepAliveCache(this)
    }
    next()
  },
  methods: {
    ...mapMutations('nav', ['updateFocus', 'updateFilterData']),
    enterHandle(_value) {
      if (_value === '') return
      let value = _value
      let label = value
      let type = 'string'
      if (typeof _value === 'object') {
        label = _value.description
        value = JSON.stringify(_value)
        type = 'object'
      }
      for (let i = 0; i < this.historyList.length; i++) {
        const v = this.historyList[i]
        if (v.value === value) {
          this.historyList.splice(i, 1)
          break
        }
      }
      const item = {
        label: label,
        value,
        type
      }
      this.historyList.unshift(item)
      localStorage.setItem('historyList', JSON.stringify(this.historyList))
      this.show = false
      this.$refs.header.blur()
      // 调用
      this.$nextTick(() => {
        let args = [this.searchValue, 'serarch_string']
        if (typeof _value === 'object') {
          args = [`${_value.attrId}_${_value.id}`, 'serarch_attr']
        }
        this.broadcast('refresh', 'refresh', args)
      })
    },
    // 更新historyList
    updateHistoryList() {
      const historyList = localStorage.getItem('historyList')
      if (historyList) {
        this.historyList = JSON.parse(historyList)
      } else {
        this.historyList = []
      }
    },
    // 删除搜索历史
    closeRemoveHandle(i) {
      if (!/^\d+$/.test(i)) {
        localStorage.removeItem('historyList')
        this.historyList = []
      } else {
        this.historyList.splice(i, 1)
        localStorage.setItem('historyList', JSON.stringify(this.historyList))
      }
    },
    clearHandle() {
      this.$refs.header.getFocus()
    },
    clickTagHandle(v) {
      if (v.type === 'object') {
        this.searchValue = v.label
        this.enterHandle(JSON.parse(v.value))
      } else {
        this.searchValue = v.label
        this.enterHandle(v.value)
      }
    },
    clickSelectedHandle(item) {
      this.$router.replace({ name: item.value })
      this.$nextTick(() => {
        this.broadcast('refresh', 'refresh')
      })
    },
    focusHandle() {
      this.show = true
      this.updateHistoryList()
    }
  }
}
</script>
<style lang="less" scoped>
.search{
  min-height: 100vh;
  width: 100vw;
  background-color: #F5F6F7;
  padding-top: 44PX;
  box-sizing: border-box;
  .nav{
    position: relative;
  }
  .active{
    font-size: 16px;
    position: relative;
    &::after{
      content: '';
      display: block;
      position: absolute;
      transform: translateX(-50%);
      bottom: -5px;
      left: 50%;
      width: 50%;
      height: 2px;
      background-color: #fff;
      border-radius: 1px;
    }
  }
  .search-panne{
    z-index: 999;
    position: absolute;
    top: 61px;
    height: calc(100vh - 121px);
    width: 100%;
    margin-top: -10px;
    background-color: #fff;
    padding: 0px 12px;
    box-sizing: border-box;
      .history-list{
        background-color: #fff;
        .history-title{
          display: flex;
          justify-content: space-between;
          align-items: center;
          line-height: 20px;
          padding: 20px 0;
          p{
            font-size: 14px;
            color: #333;
            font-weight: 500;
          }
          svg{
            font-size: 14px;
            color: #BDBDBD;
            fill: #BDBDBD;
          }
        }
        .history-tags{
          &>*{
            margin: 0 10px 10px 0;
          }
        }
      }
  }
}
.clear{
  padding-top: 0 !important;
}
.showClass{
  top: 44PX
}
</style>
<style>
.nav-item{
  color: #fff;
  font-weight: 400;
  font-size: 14px;
}
</style>
